package com.abc.def.controller;

import com.abc.def.domain.ExecCommand;
import com.abc.def.domain.Result;
import com.abc.def.util.ProcessUtil;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/process")
public class ProcessController {

    @GetMapping("/reStartProcessByName/{processName}")
    public Result reStartProcessByName(@PathVariable("processName") String processName) {
        Result result = new Result();
        boolean isRun = ProcessUtil.processIsRun(processName);
        if (isRun) {
            ProcessUtil.closeProcess(processName);
            result.setCode(200);
            result.setSuccess(true);
            result.setMsg(processName + "的进程关闭成功");
        } else {
            result.setCode(500);
            result.setSuccess(false);
            result.setMsg("未查询到" + processName + "的进程在运行");
        }
        return result;
    }

    @GetMapping("/reStartProcessByPort/{port}")
    public Result reStartProcessByPort(@PathVariable("port") int port) {
        Result result = new Result();
        Set<String> pids = ProcessUtil.getPidsByPort(port);
        if (pids.size() > 0) {
            result.setCode(200);
            result.setSuccess(true);
            result.setMsg("根据端口【" + port + "】的进程关闭成功");
        } else {
            result.setCode(500);
            result.setSuccess(false);
            result.setMsg("未查询到端口【" + port + "】的进程在运行");
        }
        result.setResult(pids);
        return result;
    }

    @PostMapping("/carry")
    public Result carry(@RequestBody ExecCommand cmd) {
        Result result = new Result();
        ProcessUtil.startBat(cmd.getCommand());
        return result;
    }
}
